#pragma once
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
using namespace std;

const int defaultbacklog = 1;

class Server
{
private:
public:
    Server(uint16_t port) : _port(port)
    {
    }

    void Init()
    {
        // 创建网络文件信息
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenfd < 0)
        {
            exit(1);
        }
        LOG(Debug, "监听文件创建完成\n");

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        // addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;

        int n = bind(_listenfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            std::cout << errno << " " << strerror(errno) << std::endl;
            exit(2);
        }
        LOG(Debug, "bind成功\n");

        n = listen(_listenfd, defaultbacklog);
        if (n != 0)
        {
            exit(3);
        }
        LOG(Debug, "监听文件开始监听\n");
    }

    void Servers(int sockfd)
    {
        char buffer[1024];
        while (true)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n == 0)
            {
                cout << "client quit" << endl;
                break;
            }
            else if (n < 0)
            {
                exit(5);
            }
            else
            {
                buffer[n] = 0;
                cout << "client say# " << buffer << endl;
                n = write(sockfd, buffer, sizeof(buffer));
                if (n < 0)
                {
                    exit(6);
                }
                LOG(Debug, "server send# %s\n", buffer);
            }
        }
    }

    void Start()
    {

 //       struct sockaddr_in addr;
//        socklen_t len = sizeof(addr);
        //int sockfd = accept(_listenfd, (struct sockaddr *)&addr, &len);
//        if (sockfd < 0)
//        {
//            exit(4);
//        }
        //LOG(Debug, "允许连接\n");
        //Servers(sockfd);
        while(1)
        {
          sleep(1);
        }
        //close(sockfd);
    }

    ~Server()
    {
    }

private:
    int _listenfd;
    // scfunc_t _Response;
    uint16_t _port;
};
